﻿using System;
using System.IO;
using System.Threading;
using Aliyun.OSS.Common;
using System.Text;
using Aliyun.OSS.Util;
using System.Security.Cryptography;
using Aliyun.OSS;

namespace zzOSSSynch
{
    class AliPutObject
    {
        static string accessKeyId = System.Configuration.ConfigurationManager.AppSettings["accessKeyId"].ToString();
        static string accessKeySecret = System.Configuration.ConfigurationManager.AppSettings["accessKeySecret"].ToString();
        static string endpoint = System.Configuration.ConfigurationManager.AppSettings["endpoint"].ToString();
        static string _bucketName = System.Configuration.ConfigurationManager.AppSettings["bucketName"].ToString();
        

        static OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);       

        static AutoResetEvent _event = new AutoResetEvent(false);
        static HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider();
        static string fileToUpload = "";

        

        public static void PutObjectFromFile(string ossPath,string _fileToUpload)
        {
            try
            {
                client.PutObject(_bucketName, ossPath, _fileToUpload);
                Console.WriteLine("Put object:{0} succeeded", ossPath);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }

        public static void PutObjectFromFileWithTimeout(string bucketName)
        {
            var _configuration = new ClientConfiguration();
            _configuration.ConnectionTimeout = 20000;
            var _client = new OssClient(endpoint, accessKeyId, accessKeySecret, _configuration);

            const string key = "PutObjectFromFile";
            try
            {
                _client.PutObject(bucketName, key, fileToUpload);
                Console.WriteLine("Put object:{0} succeeded", key);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }

        private static string GetMd5Hash(string str)
        {
            var output = new byte[128];
            var buffer = System.Text.Encoding.Default.GetBytes(str);
            hashAlgorithm.TransformBlock(buffer, 0, str.Length, output, 0);
            hashAlgorithm.TransformFinalBlock(buffer, 0, 0);
            var md5 = BitConverter.ToString(hashAlgorithm.Hash).ToLower();
            md5 = md5.Replace("-", "");
            return md5;
        }

        
        

        public static void AsyncPutObject(string ossPath, string _fileToUpload)
        {
            try
            {
                using (var fs = File.Open(_fileToUpload, FileMode.Open))
                {
                    client.BeginPutObject(_bucketName, ossPath, fs,PutObjectCallback, ossPath);

                    _event.WaitOne();
                }
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }

        private static void PutObjectCallback(IAsyncResult ar)
        {
            try
            {
                client.EndPutObject(ar);
                YFLog.logInfo("put file Success :{0}", ar.AsyncState.ToString());

            }
            catch (Exception ex)
            {
                YFLog.logInfo("put file Error:{0}{1}", ar.AsyncState.ToString(),ex.Message);
            }
            finally
            {
                _event.Set();
            }
        }

        
    }
}
